//
//  BulletView.m
//  MTGraphics
//
//  Created by 莫瑞权 on 2018/7/24.
//  Copyright © 2018年 MT. All rights reserved.
//

#import "TalkFunBulletView.h"
#import "TalkFunBulletManager.h"
#define PERFORM_IN_MAIN_QUEUE(method) if ([NSThread currentThread].isMainThread) {method}else{dispatch_async(dispatch_get_main_queue(), ^{method});}
@interface TalkFunBulletView ()

@property(nonatomic,strong)NSMutableDictionary *trackDict ;
@property(nonatomic,assign)CGFloat superlayerHeight;//记录设置过的高度
@end

@implementation TalkFunBulletView

- (NSInteger)getBulletCount
{
    return self.layer.sublayers.count;
}
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        //默认可以弹幕
        self.bulletSwitch = YES;
        
        self.maximumBullet = 30;
    }
    return self;
}
- (NSMutableDictionary * )trackDict
{
    if (_trackDict==nil) {
        _trackDict = [NSMutableDictionary dictionary];
        
    }
    return _trackDict;
}
- (void )initAvatar:(UIImage*)image content:(NSString *)content ontOfSize:(CGFloat)fontSize   textColor:(UIColor *)Color backgroundColor:(UIColor*)
backgroundColor
{

    if (content&&self.bulletSwitch) {


    PERFORM_IN_MAIN_QUEUE(
                          [self initAvatar2:image content:content ontOfSize:fontSize textColor:Color backgroundColor:backgroundColor];
                          
                        )
    }
          
}
- (void )initAvatar2:(UIImage*)image content:(NSString *)content ontOfSize:(CGFloat)fontSize   textColor:(UIColor *)Color backgroundColor:(UIColor*)backgroundColor
{
    if (self.bulletSwitch==NO&&content&&self.trackDict.count<self.maximumBullet) {
        return;
    }
    
     CGSize  size_2 =  [TalkFunTextLayer getTextWidth:@"高度" ontOfSize:fontSize];
    //表情点的空位  4位
    NSString*str  = @"    ";
    NSString*str1  = @" ";
    
        content  = [str stringByAppendingString:content];
        content  = [content stringByAppendingString:str1];
    

        
        if ( self.superlayerHeight!=self.layer.superlayer.frame.size.height||size_2.height > self.trackDict.count) {
            self.superlayerHeight = self.layer.superlayer.frame.size.height;
            
            //屏幕旋转处理
            [self.trackDict removeAllObjects];
            
            for (NSInteger i = 0; i < self.layer.superlayer.frame.size.height -(size_2.height*1.2); i++) {
                
                
                
                if ((i%5)==0) {
                    
                    [self.trackDict setObject:[NSString stringWithFormat:@"%li",i] forKey:[NSString stringWithFormat:@"%li",i]];
                }
                
            }
        }
        if (self.trackDict.count==0) {
            return;
        }
        //牵引
        CGFloat aa = self.trackDict.count - 1;
        NSArray *keys = [self.trackDict allKeys];
        //取出当前位置对应的key
        NSString *YYYY = keys[arc4random_uniform(aa)];
        
        //要删除的Y值
        NSMutableArray *Y_arr = [NSMutableArray array];
        
        for (NSInteger i = [YYYY integerValue]; i< [YYYY integerValue]+(size_2.height*2)  ; i++) {
            if ((i%5)==0) {
                [Y_arr addObject:[NSString stringWithFormat:@"%li",i]];
                
                [self.trackDict  removeObjectForKey:[NSString stringWithFormat:@"%li",i]];
                
            }
        }
        
        CGPoint point = CGPointMake(0, [YYYY integerValue]);
        
        TalkFunTextLayer *textLayer =  [[[TalkFunBulletManager alloc]init] withContent:content ontOfSize:fontSize startingPoint: point textColor:Color Avatar:image backgroundColor:backgroundColor];
        [self.layer addSublayer: textLayer];

        
        textLayer.Y_arr = Y_arr;
        textLayer.Hide_X = self.layer.superlayer.frame.size.width +arc4random_uniform(5);
        
        __weak typeof(self) weakSelf = self;
        //TOFO:动画完成,删除动画
    textLayer.animationStopBlock = ^(NSMutableArray *Y_arr, CATextLayer *layer) {
   
            
            if (Y_arr) {
                for (NSString * YY in Y_arr) {
                    //旋转屏幕前的数据
                    if ([YY integerValue]<weakSelf.layer.superlayer.frame.size.height-(size_2.height*1.2)) {
                        [weakSelf.trackDict setObject:YY forKey:YY];
                    }
                    
                }
            }
        
        if (layer) {
            [layer removeFromSuperlayer];
        }
       
            
        };
        //动画
        [textLayer startAnimation];
}
//没有头像
- (void )initWithContent:(NSString *)content ontOfSize:(CGFloat)fontSize textColor:(UIColor *)Color
{

    PERFORM_IN_MAIN_QUEUE(
                          
                          [self initWithContent2:content ontOfSize:fontSize textColor:Color];
                          
                        )
 
}

- (void )initWithContent2:(NSString *)content ontOfSize:(CGFloat)fontSize   textColor:(UIColor *)Color

{
    if (self.bulletSwitch==NO&&content&&self.trackDict.count<=self.maximumBullet) {
        return;
    }
    
            //字体高度
            CGSize  size_2 = [TalkFunTextLayer getTextWidth:@"高度" ontOfSize:fontSize];
            
            if ( self.superlayerHeight!=self.layer.superlayer.frame.size.height||size_2.height > self.trackDict.count) {
                self.superlayerHeight = self.layer.superlayer.frame.size.height;
                
                //屏幕旋转处理
                [self.trackDict removeAllObjects];
                
                //TODO:随机弹幕出现的Y, 防止重叠
                for (NSInteger i = 0; i < self.layer.superlayer.frame.size.height -(size_2.height*1.2); i++) {
                    
                    if ((i%5)==0) {
                    // NSLog(@"ssssss = %li",i);
                    [self.trackDict setObject:[NSString stringWithFormat:@"%li",i] forKey:[NSString stringWithFormat:@"%li",i]];
                    }
                    
                }
            }
            
            if (self.trackDict.count==0) {
                return;
            }
            //牵引
            CGFloat  aa = self.trackDict.count - 1;
            NSArray *keys = [self.trackDict allKeys];
            //取出当前位置对应的key
            NSString *YYYY = keys[arc4random_uniform(aa)];
            
            //要删除的Y值
            NSMutableArray *Y_arr = [NSMutableArray array];
            for (NSInteger i = [YYYY integerValue]; i< [YYYY integerValue]+(size_2.height*2)  ; i++) {
                if ((i%5)==0) {
                    [Y_arr addObject:[NSString stringWithFormat:@"%li",i]];
                    [self.trackDict  removeObjectForKey:[NSString stringWithFormat:@"%li",i]];
                }
            }
            CGPoint point = CGPointMake(0, [YYYY integerValue]);
            //TODO:创建动画layer
            TalkFunTextLayer *textLayer =  [[[TalkFunBulletManager alloc]init] withContent:content ontOfSize:fontSize startingPoint: point textColor:Color Avatar:nil backgroundColor:[UIColor clearColor]];
            [self.layer addSublayer: textLayer];
            
            textLayer.Y_arr = Y_arr;
            textLayer.Hide_X = self.layer.superlayer.frame.size.width +arc4random_uniform(5);;
            
            __weak typeof(self) weakSelf = self;
            //TOFO:动画完成,删除动画
            textLayer.animationStopBlock = ^(NSMutableArray *Y_arr, CATextLayer *layer) {
                
                if (Y_arr) {
                    for (NSString * YY in Y_arr) {
                        //旋转屏幕前的数据
                        if ([YY integerValue]<weakSelf.layer.superlayer.frame.size.height-(size_2.height*1.2)) {
                            [weakSelf.trackDict setObject:YY forKey:YY];
                        }
                        
                    }
                }
                if (layer) {
                    [layer removeFromSuperlayer];
                }
               
                
            };
            //动画
            [textLayer startAnimation];
            
}

- (void )TF_initWithContent:(NSString *)str ontOfSize:(CGFloat)fontSize textColor:(UIColor *)Color backgroundColor:(UIColor *)backgroundColor
{
    
    if (self.bulletSwitch==NO) {
        return;
    }
    NSString * content = [NSString stringWithFormat:@" %@ ",str];
    @synchronized(self){
        dispatch_async(dispatch_get_main_queue(), ^{
            //字体高度
            CGSize  size_2 =  [TalkFunTextLayer getTextWidth:@"高度" ontOfSize:fontSize];
            
            if ( self.superlayerHeight!=self.tf_height||size_2.height > self.trackDict.count) {
                self.superlayerHeight = self.tf_height;
              
                //屏幕旋转处理
                [self.trackDict removeAllObjects];
                
                //TODO:随机弹幕出现的Y, 防止重叠
                for (NSInteger i = 0; i < self.tf_height -(size_2.height*1.2); i++) {
                    
                    if ((i%5)==0) {
                    // NSLog(@"ssssss = %li",i);
                    [self.trackDict setObject:[NSString stringWithFormat:@"%li",i] forKey:[NSString stringWithFormat:@"%li",i]];
                    }
                    
                }
            }
            
            if (self.trackDict.count==0) {
                return;
            }
            //牵引
            CGFloat  aa = self.trackDict.count - 1;
            NSArray *keys = [self.trackDict allKeys];
            //取出当前位置对应的key
            NSString *YYYY = keys[arc4random_uniform(aa)];
            
            //要删除的Y值
            NSMutableArray *Y_arr = [NSMutableArray array];
            for (NSInteger i = [YYYY integerValue]; i< [YYYY integerValue]+(size_2.height*2)  ; i++) {
                if ((i%5)==0) {
                    [Y_arr addObject:[NSString stringWithFormat:@"%li",i]];
                    [self.trackDict  removeObjectForKey:[NSString stringWithFormat:@"%li",i]];
                }
            }
            CGPoint point = CGPointMake(0, [YYYY integerValue]);
            //TODO:创建动画layer
            TalkFunTextLayer *textLayer = [[[TalkFunBulletManager alloc]init] withContent:content ontOfSize:fontSize startingPoint: point textColor:Color Avatar:nil backgroundColor:backgroundColor];
            [self.layer addSublayer: textLayer];
            
            textLayer.Y_arr = Y_arr;
            textLayer.Hide_X = self.layer.superlayer.frame.size.width;
            
            __weak typeof(self) weakSelf = self;
            textLayer.animationStopBlock = ^(NSMutableArray *Y_arr, CATextLayer *layer) {
         
                
                if (Y_arr) {
                    for (NSString * YY in Y_arr) {
                        //旋转屏幕前的数据
                        if ([YY integerValue]<weakSelf.layer.superlayer.frame.size.height-(size_2.height*1.2)) {
                            [weakSelf.trackDict setObject:YY forKey:YY];
                        }
                        
                    }
                }
                
            };
            //动画
            [textLayer startAnimation ];
            
            
        });
    }
}

//停止动画
- (void)stopAnimation
{

    NSMutableArray *arrr = [NSMutableArray arrayWithArray:self.layer.sublayers];
    
    for (CALayer*slayer in arrr) {
        
        [slayer removeFromSuperlayer];
    }

    [self.trackDict removeAllObjects];

}

- (void)setBulletSwitch:(BOOL)bulletSwitch
{
    _bulletSwitch = bulletSwitch;
    
    PERFORM_IN_MAIN_QUEUE
    (
     if (bulletSwitch==NO) {
         [self stopAnimation];
     }
   
   )
    
}
@end

